from numpy import loadtxt
#调用xgboost分类器模型
from xgboost import XGBClassifier
#切分训练集和测试集
from sklearn.model_selection import train_test_split
#得出分数
from sklearn.metrics import accuracy_score
#查看特征的重要程度
from xgboost import plot_importance
#引入绘图
from matplotlib import pyplot

if __name__ == '__main__':
    #加载数据
    dataset = loadtxt('diabetes.csv',delimiter = ",")
    #划分特征，前八个是特征，最后一个Y是属于label
    X = dataset[:,0:8]
    Y = dataset[:,8]
    # print(Y)
    #随机种子
    seed = 7
    #划分训练集和测试集的占比
    test_size = 0.33
    #使用sklearn中的train_test_split化分号测试集和训练集
    X_train,X_test,y_train,y_test = train_test_split(X,Y,test_size = test_size,random_state = seed)
    #调用xgboost分类器模型,并做fit操作
    model = XGBClassifier()
    model.fit(X_train,y_train)
    #加入以下代码使得我们看待xgboost每加一颗树后数据的评估值是怎么变换的
    # eval_set = [(X_test,y_test)]
    # model.fit(X_train,y_train,early_stopping_rounds = 10,eval_metric = "logloss",eval_set = eval_set,verbose = True)
    #做预测
    plot_importance(model)
    pyplot.show()
    y_pred = model.predict(X_test)
    # print(y_pred)
    predictions = [round(value) for value in y_pred]
    #评估预测
    accuracy = accuracy_score(y_test,predictions)
    print("accuracy:%.2f%%" % (accuracy * 100.0))
